
/**
 * Created by ting.zhang on 2020/01/20.
 */
import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import { Card, Button, Spin, message, Affix, Popover} from 'antd';
import ZxTicketInfo from 'containers/request/travel-request/travel-slide/zx-ticket-info'
import travelService from 'containers/request/travel-request/travel.service'

class ZxRecommendConfirm extends React.Component{
  supply = {};
  constructor(props){
    super(props);
    this.state = {
      isLoading: false,
      refundRules: {} //退改签规则
    };
  }

  //初始化编辑数据
  componentWillReceiveProps(){
    const { info, selectedTickets } = this.props.params;
  }

  componentWillMount(){
    const { params } = this.props;
  }

  // 确认预定
  toSubmit = () => {
    this.setState({isLoading: true});
    const {info, selectedTickets = []} = this.props.params;
    let changeFlightList = [], noChangeFlightList = [];
    selectedTickets.map(ticket => {
      ticket.isRecommend ? changeFlightList.push({
        subCustomerOrderId: ticket.orgOrderInfo.subCustomerOrderId,
        journeyId: ticket.orgOrderInfo.journeyId,
        newPriceId: ticket.priceId, //变更行程时，选择的新机票价格id，变更时必填
        beyondBufferAllowSubmit: 1 //超出buffer允许提交,1：允许
      }) : noChangeFlightList.push({
        subCustomerOrderId: ticket.subCustomerOrderId,
        journeyId: ticket.journeyId,
      });
    });

    travelService.confirmBook({
      businessCode: info.businessCode,
      changeFlightList,
      noChangeFlightList
    }).then(res => {
      this.setState({
        isLoading: false
      });
      if (res && res.status == 200 && res.data && res.data.success) {
        this.closeSlide('0');
      } else {
        message.error(res.data.message);
      }
    }).catch(e => {
      this.setState({isLoading: false});
      const msg = (e.response && e.response.data && e.response.data.message) || messages('common.operate.filed');
      message.error(msg);
    });
  };

  // 重新选择
  reChoose = () => {
    this.closeSlide('1');
  };

  // 返回
  goBack = () => {
    this.closeSlide('2');
  };

  // 关闭侧滑
  closeSlide = (flag, item, index) => {
    this.props.close(item ? {flag, item, index} : {flag});
  };

  // 修改航班
  changeAirline = (item, index) => {
    console.log('-----修改航班-----');
    this.closeSlide('3', item, index);
  };

  //获取星期几
  getWeed = (value) => {
    switch(value) {
      case 0:
        return messages('request.key33'/*周日*/);
      case 1:
        return messages('request.key34'/*周一*/);
      case 2:
        return messages('request.key35'/*周二*/);
      case 3:
        return messages('request.key36'/*周三*/);
      case 4:
        return messages('request.key37'/*周四*/);
      case 5:
        return messages('request.key38'/*周五*/);
      case 6:
        return messages('request.key39'/*周六*/);
    }
  };

  showTicketChangeRule = (item) => { // 显示退改签政策
    console.log('---showTicketChangeRule-----', item);
    const {priceId, refundChangeRule, subCustomerOrderId} = item;
    let refundRules = {};
    if (subCustomerOrderId) {
      refundRules = JSON.parse(refundChangeRule || '{}');
      this.setState({refundRules});
    } else {
      travelService.queryRefundChangeRuleBefore({priceId}).then(res => {
        if (res && res.status === 200 && res.data && res.data.body) {
          refundRules = res.data.body;
        }
        this.setState({refundRules});
      }).catch(e => {});
    }
  };

  render() {
    const {isLoading, refundRules} = this.state;
    const {info, selectedTickets = []} = this.props.params;
    let supplierName = selectedTickets[0] && selectedTickets[0].supplierName;
    if (!supplierName) {
      const supplierCode = selectedTickets[0] && selectedTickets[0].supplierCode;
      supplierName = messages(`zx.flight.code.${supplierCode}`);
    }
    const {flightNo,preRefundAmount,preChangeAmount,baggage,signTransferRule,refundRuleDetailList,changeRuleDetailList} = refundRules;
    let totalAmt = 0,
      recommendNum = 0,
      orgNum = 0;
    let refundRulesContent = (
      <div className="refund-rule-wrapper">
        <div><span className="rule-label">{messages('request.key76'/*航班号*/)}：</span>{flightNo}</div>
        <div><span className="rule-label">{messages('zx.rule.package'/*行李额度*/)}：</span>{baggage}</div>
        <div><span className="rule-label">{messages('zx.rule.sign.transfer'/*签转规则*/)}：</span>{signTransferRule}</div>
        <div><span className="rule-label">{messages('zx.rule.pre.change'/*预估改签费*/)}：</span>{preChangeAmount}</div>
        <div><span className="rule-label">{messages('zx.rule.pre.refund'/*预估退票费*/)}：</span>{preRefundAmount}</div>
        <div>
          <div className="rule-label">{messages('zx.rule.change'/*改签规则*/)}：</div>
          {changeRuleDetailList && changeRuleDetailList.map(obj => (
            <div>{obj.timeScope}：{obj.percent.indexOf('%') < 0 ? obj.percent : messages('zx.rule.percent', {n: obj.percent})}</div>
          ))}
        </div>
        <div>
          <div className="rule-label">{messages('zx.rule.refund'/*退票规则*/)}：</div>
          {refundRuleDetailList && refundRuleDetailList.map(obj => (
            <div>{obj.timeScope}：{obj.percent.indexOf('%') < 0 ? obj.percent : messages('zx.rule.percent', {n: obj.percent})}</div>
          ))}
        </div>
      </div>
    );
    return (
      <div className="zx-recommend-confirm">
        <div>
          <Card className="top-hint" key="0">
            <div className="top-hint-highlight">{messages('zx.reconfirm'/*重新选择后的航班信息，请确认预定*/)}</div>
            <div className="">{messages('zx.reconfirm.note'/*该订单由{name}提供服务，若预定时遇到问题可拨打客户专线*/, {name: supplierName})}</div>
          </Card>
        </div>
        <div className="confirm-list">
          {selectedTickets.map((item, index) => {
            let {departureDate, isRecommend, totalAmount, supplierServiceFee} = item;
            departureDate = departureDate && departureDate.replace ? departureDate.replace(/-/g, '/') : departureDate;
            let dataStr = `${new Date(departureDate).format('yyyy.MM.dd')}${this.getWeed(new Date(departureDate).getDay())}
                ${item.departureCityName} - ${item.arrivalCityName} `;

            totalAmount && (item.subOrderTotalAmount = totalAmount - supplierServiceFee);
            totalAmt = totalAmt + Number(item.subOrderTotalAmount || 0);
            isRecommend ? recommendNum++ : orgNum++;
            return <Card className="confirm-list-item" key={index+1}>
              <div className="confirm-header">
                <span className="n-segment">{messages('zx.n.segment'/*第{n}程*/, {n: index+1})}</span>
                <span className={`tag  ${item.isRecommend && 'recommend-tag'}`}>
                  {item.isRecommend ? messages("zx.recommend.airline"/*推荐航班*/) : messages("zx.org.airline"/*原行程*/)}
                </span>
                <span className="time-info">{dataStr}</span>
                <span className="change-airline" onClick={() => {this.changeAirline(item, index)}}>{messages("zx.change.flight"/*修改航班*/)}</span>
              </div>
              <div className="confirm-content">
                <div className="date-str">{dataStr}
                  <span className="refund" onClick={() => this.showTicketChangeRule(item)}>
                    <Popover placement="right"
                             trigger="click"
                             title={messages('zx.change.refund.policy', {cm: '退改签政策'})}
                             content={refundRulesContent}
                             overlayStyle={{maxWidth: 500}}>{messages('zx.change.refund.policy', {cm: '退改签政策'})}</Popover>
                  </span>
                </div>
                <ZxTicketInfo ticketInfo={item} withTax/>
              </div>
            </Card>;
          })}
        </div>
        <div className="total-info">
          <div className="total-label">{messages("zx.order.total.amt"/*订单金额总计*/)}&nbsp;
            <span className="total-price">CNY {this.filterMoney(totalAmt)}</span>
          </div>
          <div className="num">{messages("zx.recommend.flight.count"/*推荐航班{n}程，原航班{m}程*/, {n: recommendNum, m: orgNum})}</div>
        </div>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button onClick={this.toSubmit} type="primary" loading={isLoading}>{messages('zx.confirm.book.btn'/*确认预定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.reChoose} >{messages('zx.choose.again'/*重新选择*/)}</Button>
          <Button className="travel-type-btn" onClick={this.goBack} >{messages('common.back'/*返回*/)}</Button>
        </Affix>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { language: state.main.language };
}

export default connect(mapStateToProps)(ZxRecommendConfirm);
